﻿namespace EyeSoft.Wpf.Facilities.Demo
{
	using System;
	using System.Windows;
	using System.Windows.Threading;

	using EyeSoft.Wpf.Facilities.Demo.Configuration;
	using EyeSoft.Wpf.Facilities.Demo.ViewModels;

	public partial class App
	{
		public App()
		{
			if (this.IsAlreadyRunning())
			{
				return;
			}

			Current.Dispatcher.Thread.Name = "UI Thread";

			ContainerRegister.Initialize();

			AppDomain.CurrentDomain.UnhandledException += (s, e) => CatchUnhandledException(s, (Exception)e.ExceptionObject);
			DispatcherUnhandledException += CatchDispacherUnhandledException;

			DialogService.ShowMain<MainViewModel>();
		}

		private void CatchDispacherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
		{
			ShowError(e.Exception);
		}

		private void CatchUnhandledException(object sender, Exception e)
		{
			ShowError(e);
		}

		private void ShowError(Exception exception)
		{
			var message = "Message: {0}".NamedFormat(exception.Message);
			DialogService.ShowMessage("Unandler error", message, MessageBoxButton.OK, MessageBoxImage.Error);
		}
	}
}